package com.emin.platform.subjectcenter.api;


import com.emin.base.exception.EminException;
import com.emin.platform.subjectcenter.common.configure.Configure;
import com.emin.platform.subjectcenter.common.response.ResponseBack;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import static com.emin.platform.subjectcenter.exception.ExceptionCode.SYSTEM_ERROR;


/**
 * 文件上传Controller
 *
 * @author Jack
 * @version V1.0
 * @Title:
 * @Description: 用于上传图片等
 * @date 2017/10/25 11:31
 */
@Controller
@RequestMapping("/file")
public class UploadController {


    private static final int IMG_UPLOAD_MAX_SIZE_LIMIT_DEFAULT = 3 * 1024 * 1024;


    @Autowired
    private Configure configure;

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);


    /**
     * 这个方法是使用springMVC解析器进行文件上传</br>
     * 下面那个方法是使用字符流写入方式进行文件上传</br>
     * 使用springMVC解析器进行文件上传b比使用字符流写入方式进行文件上传效率高</br>
     *
     * @param files   文件
     * @param request 用户http请求
     * @return 返回接口处理的状态
     * @author Jack
     * @serialData 2017-3-15
     * @since 1.0.1
     **/
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;" +
            "charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "上传主体图标", tags = {"主体中心基本信息API"}, httpMethod = "POST",
            produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", paramType = "form", dataType = "file"),
    })
    public ResponseBack<String> upload(@RequestParam("file") CommonsMultipartFile[] files,
                                       HttpServletRequest
                                               request) {
        try {
            String filePathstr = configure.getFilePath();
            String fileName = " ";
            String fileUrl = " ";
            int i = 0;
            // for (int i = 0; i < files.length; i++) {
            LOGGER.info("fileName={},originalName={}", files[i].getName(), files[i]
                    .getOriginalFilename());
            String tartget = "/images/";
            String fileRealPath = filePathstr + tartget;
            if (StringUtils.isBlank(fileRealPath)) {
//                return ResponseBack.error(SYSTEM_ERROR);
                return null;
            }
            LOGGER.info("fileRealPath---------->" + fileRealPath);
            File realDir = new File(fileRealPath);
            if (!realDir.exists()) {
                realDir.mkdirs();
            }
            if (!files[i].isEmpty()) {
                // 拿到输出流，同时重命名上传的文件
                fileName = new Date().getTime() + files[i].getOriginalFilename();
                // 这个值保存到数据库
                fileUrl = tartget + fileName;
                FileOutputStream os = new FileOutputStream(fileRealPath + fileName);
                // 拿到上传文件的输入流
                FileInputStream in = (FileInputStream) files[i].getInputStream();
                LOGGER.info("in---------->" + in.available());
                byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
                int length = 0;
                // 以写字节的方式写文件
                while ((length = in.read(buf)) > 0) {
                    os.write(buf, 0, length);
                }
                os.flush();
                os.close();
                in.close();
            }
            //}
            // 保存图片路径
            return ResponseBack.success(fileRealPath + fileName);
        } catch (EminException e) {
            return ResponseBack.error(e);
        } catch (Exception e) {
            return ResponseBack.error(SYSTEM_ERROR);
        }

    }


    /**
     * 查询头像接口</br>
     * 流程:
     * 1.校验参数是否正确</br>
     * 2.调用查询图片服务</br>
     *
     * @param request 用户http请求参数
     * @return JsonCommon<OrderCommonBack> 返回的HTTP请求结果
     * @author chenjinke
     * @date 2017/3/16
     * @desc
     * @see
     */
    @RequestMapping(value = "/getImage", method = RequestMethod.GET, produces =
            "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "获取主体图标", tags = {"主体中心基本信息API"}, httpMethod = "GET",
            produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileRealPath", paramType = "path", dataType = "string",
                    value =
                            "主体图标绝对地址，从上传图标接口的返回值中获取"),
    })
    public ResponseBack<Boolean> getImage(HttpServletRequest request, HttpServletResponse
            response) {
        try {
            String fileRealPath = request.getParameter("fileRealPath");
            File file = new File(fileRealPath);
            // 判断文件是否存在如果不存在就返回默认图标
            if (!(file.exists() && file.canRead())) {
                file = new File(request.getSession().getServletContext().getRealPath("/") +
                        "/images/head_default.png");
            }
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            response.setContentType("image/png,jpg");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
            return ResponseBack.success(true);
        } catch (EminException e) {
            return ResponseBack.error(e);
        } catch (Exception e) {
            return ResponseBack.error(SYSTEM_ERROR);
        }

    }


}